//
// Created by 陈成 on 2020/1/6.
//

#include "MarsExplorationProgram.h"

const std::map<char, Direction> MarsExplorationProgram::direction_mapping = {
        {'E', EAST},
        {'S', SOUTH},
        {'W', WEST},
        {'N', NORTH},
};

int
MarsExplorationProgram::initWithFile(std::string input_filename) {
    FILE *fp = fopen(input_filename.c_str(), "r");
    if (nullptr == fp)
        return EXIT_FAILURE;

    auto width{0};
    auto height{0};
    if (fscanf(fp, "%d %d\n", &width, &height) != EOF) {
        d_mars_highland_p = new MarsHighland{width, height};
    }

    while (true) {
        auto x{0};
        auto y{0};
        auto direction{'N'};

        if (fscanf(fp, "%d %d %c\n", &x, &y, &direction) != EOF) {
            Direction d = direction_mapping.at(direction);
            MarsRover mr{x, y, d};

            char commands[100];
            if (fscanf(fp, "%s\n", commands) != EOF) {
                mr.setCommands(std::string{commands});
                d_mars_rovers.push_back(mr);
            } else {
                break;
            }
        } else {
            break;
        }
    }

    fclose(fp);

    return EXIT_SUCCESS;
}

MarsHighland *
MarsExplorationProgram::getMarsHighland() const {
    return d_mars_highland_p;
}

MarsExplorationProgram::MarsExplorationProgram() {

}

MarsExplorationProgram::~MarsExplorationProgram() {
    if (d_mars_highland_p) delete d_mars_highland_p;
}

std::vector<MarsRover> &
MarsExplorationProgram::getMarsRovers() {
    return d_mars_rovers;
}

int
MarsExplorationProgram::start() {
    for (auto &mr : d_mars_rovers) {
        int rslt = mr.explore(d_mars_highland_p);

        if (EXIT_FAILURE == rslt)
            return rslt;
    }

    return EXIT_SUCCESS;
}
